// \u4e00-\u9fa5] 中文验证规则
import validate from 'wechat-validate'
import { uploadAPI } from '../../../api/public'
import { addhouseAPI, detailhouseAPI } from '../../../api/houseapi'
Page({
   // 通过 behaviors 注入 validate 方法
  behaviors: [validate],
  data: {
    idcardFrontUrl: '',
    idcardBackUrl: '',
    point:'',
    building:'',
    room:'',
    name:'',
    gender:1,
    mobile:'',
    id:undefined,
  },
   rules: {
    name: [
      { required: true, message: '请填写姓名!' },
      { pattern: /^(?:[\u4e00-\u9fa5·]{2,4})$/, message: '请检查姓名是否正确!' }
    ],
    mobile: [
      { required: true, message: '请填写手机号!' },
      { pattern: /^1\d{10}$/, message: '请检查手机号是否正确!' },
    ],
    idcardFrontUrl: [{ required: true, message: '请上传身份证正面!' }],
    idcardBackUrl: [{ required: true, message: '请上传身份证国徽面!' }]
  },
  // goList() {
  //   wx.reLaunch({
  //     url: '/house_pkg/pages/list/index',
  //   })
  // },
  removePicture(ev) {
    // 移除图片的类型（身份证正面或反面）
    // console.log(ev);
    const type = ev.mark?.type
    this.setData({ 
      [type]: '',
    })
  },
  // 接受页面传值 更新数据
  onLoad({point,building,room,id}) {
    // console.log(e);
    if (id) {
      this.setData({id})
      this.detailhouse(id)
      wx.setNavigationBarTitle({
        title:'编辑房屋信息'
      })
    }else{
      this.setData({point,building,room})
    }
    
  },
  // 编辑回显页面onload拿到id
  async detailhouse(id) {
    const res = await detailhouseAPI(id)
    console.log(res)
    // eslint-disable-next-line no-unused-vars
    const {status,...data} = res.data
    this.setData({
      ...data
    })
  },

  // 验证所有表单提交接口
  async formsubmit() {
     // 验证码 rules 中定义的全部数据
    const isAllValid = this.validate()
    if(!isAllValid) return
    // console.log(this.data);
    // eslint-disable-next-line no-unused-vars
    const {__webviewId__,...body} = this.data
    console.log(body);
    const res = await addhouseAPI(body)
    console.log(res);
    wx.navigateBack({
      delta: this.data.id ? 2 : 4
    })
  },
  // 上传图片
  async uploadimg(e){
    console.log(e);
    const res = await wx.chooseMedia({
      // 限制图片数量和类型
      count:1,
      mediaType:['image']
    })
    console.log(res)
    // 取得图片路径
    const filepath = res.tempFiles[0].tempFilePath
    // console.log(filepath);
    // 限制上传图片大小
    if (res.tempFiles[0].size > 5 * 1024 * 1024) {
      return wx.utils.toast('文件小于1m')
    }
    const uploadimg = await uploadAPI(filepath)
    console.log(uploadimg);
    this.setData({
      [e.mark.type] : uploadimg.data.url
    })
  }
})
